package com.cloud.bssp.nio.filechannel;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description： 获取FileChannel
 * @author：weirx
 * @date：2021/11/3 10:02
 * @version：3.0
 */
public class GetFileChannel {

    public static void main(String[] args) throws Exception {
        //使用FileInputStream获取channel
        FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\P50\\Desktop\\text.txt"));
        FileChannel channel1 = fileInputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(10);
        channel1.read(buffer);
        buffer.flip();
        System.out.println((print(buffer)));
        fileInputStream.close();
        //使用FileOutputStream获取channel
//        FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\P50\\Desktop\\text.txt"),true);
//        FileChannel channel2 = fileOutputStream.getChannel();
//        ByteBuffer buffer = ByteBuffer.allocate(10);
//        buffer.put(StandardCharsets.UTF_8.encode("helloworld"));
//        buffer.flip();
//        channel2.write(buffer);

        //使用RandomAccessFile获取channel
//        RandomAccessFile file = new RandomAccessFile("C:\\Users\\P50\\Desktop\\text.txt", "rw");
//        FileChannel channel3 = file.getChannel();
//        ByteBuffer buffer = ByteBuffer.allocate(15);
//        //读取文件内容到buffer
//        channel3.read(buffer);
//        buffer.flip();
//        System.out.println(print(buffer));
//
//        // 切换为写模式，并且清空buffer
//        buffer.clear();
//        //写入helloworld到文件
//        buffer.put(StandardCharsets.UTF_8.encode("helloworld"));
//        buffer.flip();
//        channel3.write(buffer);
    }

    static String print(ByteBuffer b) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < b.limit(); i++) {
            stringBuilder.append((char) b.get(i));
        }
        return stringBuilder.toString();
    }
}
